//
//  ClubCreatAddressViewController.swift
//  77Club
//
//  Created by Apple on 2024/9/20.
//

import UIKit

class ClubCreateAddressViewController: ClubBaseViewController {

    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("创建新地址").color(.black).font(16.font_semiBold).end()
    private let delButton = c_make_ex(UIButton.self)
        .text("删除").color("#FF8319").font(16.font_medium).end()
    private let whiteBgView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12).end()
    private let addressLabel = c_make_ex(UILabel.self)
        .text("填写地址").color("#2E3033").font(16.font_semiBold).end()
    private var defaultButton = UIIconButton(style: .leading(itemSpace: 0))
    private let oneLineView = c_make_ex(UIView.self)
        .bgColor("#E8E9EB").end()
    private let twoLineView = c_make_ex(UIView.self)
        .bgColor("#E8E9EB").end()
    private let threeLineView = c_make_ex(UIView.self)
        .bgColor("#E8E9EB").end()
    private let fourLineView = c_make_ex(UIView.self)
        .bgColor("#E8E9EB").end()
    private let peopleLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(14.font_medium)
        .text("收货人").end()
    private let phoneLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(14.font_medium)
        .text("手机号").end()
    private let zhifuNameLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(14.font_medium)
        .text("支付宝姓名").end()
    private let zhifuAccLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(14.font_medium)
        .text("支付宝账号").end()
    private let infoLabel = c_make_ex(UILabel.self)
        .color("#2E3033").font(14.font_medium)
        .text("详细信息").end()
    private let peopleTextField = c_make_ex(UITextField.self)
        .color("#2E3033").font(14.font_medium)
        .placeholder("请填写收货人姓名").end()
    private let phoneTextField = c_make_ex(UITextField.self)
        .color("#2E3033").font(14.font_medium)
        .placeholder("请填写收货人手机号").end()
    private let zhifuNameTextField = c_make_ex(UITextField.self)
        .color("#2E3033").font(14.font_medium)
        .placeholder("虚拟商品请填写支付宝姓名").end()
    private let hifuAccTextField = c_make_ex(UITextField.self)
        .color("#2E3033").font(14.font_medium)
        .placeholder("虚拟商品请填写支付宝账号").end()
    private let infoTextView = c_make_ex(UITextView.self)
        .color("#2E3033").font(14.font_medium).end()
    private let cleanButton = c_make_ex(UIButton.self)
        .image("Mine_address_clean").end()
    private let placeholderLabel = c_make_ex(UILabel.self)
        .color("#AEB0B3").font(14.font_medium)
        .text("街道、门牌号等").end()
    private let saveButton = c_make_ex(UIButton.self)
        .bgColor("#FF831A").color(.white).text("保存")
        .font(16.font_semiBold).corner(22).end()
    
    var isEdit: Bool = false {
        didSet{
            if isEdit {
                self.titleLabel.text = "编辑地址"
                self.delButton.isHidden = false
            }else{
                self.titleLabel.text = "创建新地址"
                self.delButton.isHidden = true
            }            
        }
    }
    var model: ClubMineAddressModel?{
        didSet{
            guard let md = model else { return }
            
            self.peopleTextField.text = md.consignee
            self.phoneTextField.text = md.mobile
            self.infoTextView.text = md.uaddress
            self.zhifuNameTextField.text = md.bank_user
            self.hifuAccTextField.text = md.bank_id
            self.placeholderLabel.isHidden = true
            self.cleanButton.isHidden = false
        }
    }
    var updateAddressData: (() -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            delButton
            whiteBgView.subviews{
                addressLabel
                defaultButton
                oneLineView
                twoLineView
                threeLineView
                fourLineView
                peopleLabel
                phoneLabel
                zhifuNameLabel
                zhifuAccLabel
                infoLabel
                peopleTextField
                phoneTextField
                zhifuNameTextField
                hifuAccTextField
                infoTextView
                placeholderLabel
                cleanButton
            }
            saveButton
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.Leading == backButton.Trailing
        titleLabel.CenterY == backButton.CenterY
        delButton.trailing(0).top(.statusHeight).width(80).height(44)
        whiteBgView.leading(12.0.Scale).trailing(12.0.Scale).top(.navi_height + 11.0.Scale)
        addressLabel.leading(12.0.Scale).top(12.0.Scale)
        defaultButton.trailing(12.0.Scale).top(12.0.Scale).height(22.0.Scale).width(100)
        oneLineView.leading(12.0.Scale).trailing(12.0.Scale).height(1).top(96.0.Scale)
        twoLineView.leading(12.0.Scale).trailing(12.0.Scale).height(1)
        twoLineView.Top == oneLineView.Bottom + 50.0.Scale
        threeLineView.leading(12.0.Scale).trailing(12.0.Scale).height(1)
        threeLineView.Top == twoLineView.Bottom + 50.0.Scale
        fourLineView.leading(12.0.Scale).trailing(12.0.Scale).height(1)
        fourLineView.Top == threeLineView.Bottom + 50.0.Scale
        peopleLabel.leading(12.0.Scale)
        peopleLabel.Bottom == oneLineView.Top - 18.0.Scale
        phoneLabel.leading(12.0.Scale)
        phoneLabel.Top == oneLineView.Bottom + 18.0.Scale
        zhifuNameLabel.leading(12.0.Scale)
        zhifuNameLabel.Top == twoLineView.Bottom + 18.0.Scale
        zhifuAccLabel.leading(12.0.Scale)
        zhifuAccLabel.Top == threeLineView.Bottom + 18.0.Scale
        infoLabel.leading(12.0.Scale)
        infoLabel.CenterY == infoTextView.CenterY
        peopleTextField.leading(102.0.Scale).height(40)
        peopleTextField.CenterY == peopleLabel.CenterY
        phoneTextField.leading(102.0.Scale).height(40)
        phoneTextField.CenterY == phoneLabel.CenterY
        zhifuNameTextField.leading(102.0.Scale).height(40)
        zhifuNameTextField.CenterY == zhifuNameLabel.CenterY
        hifuAccTextField.leading(102.0.Scale).height(40)
        hifuAccTextField.CenterY == zhifuAccLabel.CenterY
        infoTextView.leading(102.0.Scale).trailing(44.0.Scale).height(40).bottom(16.0.Scale)
        infoTextView.Top == fourLineView.Bottom + 18.0.Scale
        placeholderLabel.leading(104.0.Scale)
        placeholderLabel.CenterY == infoTextView.CenterY
        cleanButton.trailing(12.0.Scale).size(24.0.Scale)
        cleanButton.CenterY == infoTextView.CenterY
        
        saveButton.leading(24).trailing(24).height(44.0.Scale).bottom(.safe_bottom)
        infoTextView.delegate = self
        infoTextView.isScrollEnabled = false
        infoTextView.tintColor = "#2E3033".toColor
        defaultButton.isHidden = true
        cleanButton.isHidden = true
        
        defaultButton.style { v in
            v.iconSize = CGSize(width: 22.0.Scale, height: 22.0.Scale)
            v.setImage("Mine_address_check".toImage, for: .normal)
            v.setImage("Mine_address_checked".toImage, for: .selected)
            v.setTitleColor("#323233".toColor, for: .normal)
            v.setTitleColor("#FF8319".toColor, for: .selected)
            v.setTitle("默认收货地址", for: .normal)
            v.titleLabel?.font = 12.font_regular
        }
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        defaultButton.addTarget(self, action: #selector(clickDefaultButton), for: .touchUpInside)
        cleanButton.addTarget(self, action: #selector(clickCleanButton), for: .touchUpInside)
        delButton.addTarget(self, action: #selector(clickDelButton), for: .touchUpInside)
        saveButton.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
    }

}

extension ClubCreateAddressViewController: UITextViewDelegate {
    
    @objc private func clickSaveButton(){
        
        guard let name = peopleTextField.text, name.count > 0 else {
            "请输入收货人姓名".toast_error
            return
        }
        guard let phone = phoneTextField.text, phone.count > 0 else {
            "请输入手机号".toast_error
            return
        }
        guard let zhifuName = zhifuNameTextField.text, zhifuName.count > 0 else {
            "请输入支付宝姓名".toast_error
            return
        }
        guard let zhifuAcc = hifuAccTextField.text, zhifuAcc.count > 0 else {
            "请输入支付宝账号".toast_error
            return
        }
        guard let info = infoTextView.text, info.count > 0 else {
            "请输入详细信息".toast_error
            return
        }
        
        let dict = [
            "consignee": name,
            "mobile": phone,
            "uaddress": info,
            "bank_user": zhifuName,
            "bank_id": zhifuAcc,
            "moren": "0",
        ] as [String : Any]
        
        guard let jsonStr = ClubGlobalTool.shared.convertToJsonData(dict) else { return }
        guard let encryStr = ClubGlobalTool.shared.AES128Encrypt(plainText: jsonStr, key: "mtetbpryjhdxmnhx") else { return }
        
        Task{
            let res = await network.requestSpecial(.addAddress(value: encryStr))
            if res.isSuccess {
                updateAddressData?()
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    @objc private func clickDelButton(){
        
        guard let addressID = model?.id else { return }
        Task {
            let res = await network.requestSpecial(.delAddress(addressID: addressID))
            if res.isSuccess {
                updateAddressData?()
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    @objc private func clickCleanButton(){
        infoTextView.text = ""
        self.placeholderLabel.isHidden = false
        self.cleanButton.isHidden = true
        adjustTextViewHeight()
    }
    
    @objc private func clickDefaultButton(){
        defaultButton.isSelected = !defaultButton.isSelected
    }
    
    // 当文本发生变化时调整UITextView高度
    func textViewDidChange(_ textView: UITextView) {
        placeholderLabel.isHidden = !textView.text.isEmpty
        cleanButton.isHidden = textView.text.isEmpty
        adjustTextViewHeight()
    }
        
    // 调整UITextView的高度
    func adjustTextViewHeight() {
        let size = CGSize(width: infoTextView.frame.width, height: .infinity)
        let estimatedSize = infoTextView.sizeThatFits(size)
        infoTextView.heightConstraint?.constant = estimatedSize.height
    }
}
